package com.ld.security.gateway.filter;

import com.ld.security.gateway.feign.AuthClientFeign;
import com.ld.security.gateway.feign.AuthUserFeign;
import com.ld.security.gateway.feign.FunctionPo;
import com.ld.security.gateway.feign.FunctionVo;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//@Component
@Log
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthClientFeign authClientFeign;

    @Autowired
    private AuthUserFeign authUserFeign;

    private String serverKey="serverToken";
    private String userKey="userToken";

    private String rpcKey="rpc";
    private String apiKey="api";

    private boolean test=true;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        String url = request.getURI().getPath();
        FunctionPo po =  new FunctionPo();
        po.setUrl(url);
        FunctionVo vo = new  FunctionVo();
        vo.setAuthResult(true);
        try{
            if(TokenUtil.splitStr(url,2,apiKey)){
                log.info("前端请求"+url);
                String token = TokenUtil.getToken(request,userKey);
                po.setToken(token);
              //  vo = authUserFeign.hasPermission(po).getData();
            }else if(TokenUtil.splitStr(url,2,rpcKey)){
                log.info("服务请求"+url);
                String token = TokenUtil.getToken(request,serverKey);
                po.setToken(token);
            //    vo = authClientFeign.hasPermission(po).getData();
            }

        }    catch (Exception e){
            e.printStackTrace();
        }

        if(vo.isAuthResult()){
            return chain.filter(exchange);
        }else{
            log.info("无访问权限："+vo.getMessage());
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

    }

    @Override
    public int getOrder() {
        return -100;
    }
}